using AutoBackupSql.Models;
using AutoBackupSql.Services;
using Microsoft.Extensions.Options;
using Quartz;

namespace AutoBackupSql.Jobs
{
    public class BackupJob : IJob
    {
        private readonly ILogger<BackupJob> _logger;
        private readonly MySqlBackupService _backupService;
        private readonly FileTransferService _transferService;
        private readonly IOptions<BackupSettings> _settings;

        public BackupJob(
            ILogger<BackupJob> logger,
            MySqlBackupService backupService,
            FileTransferService transferService,
            IOptions<BackupSettings> settings)
        {
            _logger = logger;
            _backupService = backupService;
            _transferService = transferService;
            _settings = settings;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("开始执行备份任务: {Time}", DateTime.Now);

            var retryCount = 0;
            var maxRetries = _settings.Value.BackupSchedule.MaxRetries;

            while (retryCount <= maxRetries)
            {
                try
                {
                    // 步骤1: 测试数据库连接
                    if (!await _backupService.TestConnectionAsync())
                    {
                        throw new Exception("数据库连接失败");
                    }

                    // 步骤2: 测试目标服务器连接
                    if (!await _transferService.TestConnectionAsync())
                    {
                        throw new Exception("目标服务器连接失败");
                    }

                    // 步骤3: 创建MySQL备份
                    var backupFilePath = await _backupService.CreateBackupAsync();

                    // 步骤4: 传输备份文件到目标服务器
                    var remotePath = Path.Combine(_settings.Value.TargetServer.BackupPath, Path.GetFileName(backupFilePath));
                    if (!await _transferService.TransferFileAsync(backupFilePath, remotePath))
                    {
                        throw new Exception("文件传输失败");
                    }

                    // 步骤5: 验证文件传输成功
                    if (!await _transferService.FileExistsAsync(remotePath))
                    {
                        throw new Exception("远程文件验证失败");
                    }

                    // 步骤6: 清理本地过期备份
                    _backupService.CleanupOldBackups();

                    _logger.LogInformation("备份任务执行成功");
                    return; // 成功完成，退出重试循环
                }
                catch (Exception ex)
                {
                    retryCount++;
                    _logger.LogError(ex, "备份任务执行失败 (尝试 {RetryCount}/{MaxRetries})", retryCount, maxRetries + 1);

                    if (retryCount <= maxRetries)
                    {
                        var delayMinutes = _settings.Value.BackupSchedule.RetryIntervalMinutes;
                        _logger.LogInformation("等待 {DelayMinutes} 分钟后重试", delayMinutes);
                        await Task.Delay(TimeSpan.FromMinutes(delayMinutes));
                    }
                    else
                    {
                        _logger.LogError("备份任务最终失败，已达到最大重试次数");
                        throw; // 重新抛出异常，让Quartz知道任务失败
                    }
                }
            }
        }
    }
}